package cn.gailvlun.gll.presentation.apartment;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityApartmentBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.apartment.room.GetRoomListReq;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.net.apartment.room.RoomStatus;
import cn.gailvlun.gll.net.apartment.room.RoomTag;
import cn.gailvlun.gll.presentation.apartment.adapter.ApartmentAdapter;
import cn.gailvlun.gll.presentation.apartment.bean.SkillViewModel;
import cn.gailvlun.gll.presentation.base.App;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.NavigationBarView;



public class ApartmentActivity extends BaseActivity
        implements OnRefreshListener, OnLoadmoreListener {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, ApartmentActivity.class);
        context.startActivity(intent);
    }
    public static void openFromNotification(Context context) {
        Intent intent = new Intent(context, ApartmentActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private ApartmentAdapter mAdapter;
    private GridLayoutManager mLayoutManager;

    private ActivityApartmentBinding mBinding;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_apartment);

        mAdapter = new ApartmentAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new GridLayoutManager(mContext, 4);
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (position) {
                    case 0: {
                        return 4;
                    }
                    case 1:
                    case 2:
                    case 3:
                    case 4: {
                        return 1;
                    }
                    default: {
                        return 4;
                    }
                }
            }
        });
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.refreshLayout.setOnRefreshListener(this);
        mBinding.refreshLayout.setOnLoadmoreListener(this);
        mBinding.refreshLayout.setEnableLoadmore(false);

        loadRecyclerView(null, true, false);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                ApartmentManageActivity.openActivity(mContext);
            }
        });
    }

    private GetRoomListReq mGetRoomListReq = new GetRoomListReq();

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mBinding.refreshLayout.autoRefresh(0);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mGetRoomListReq.resetPage();
        HttpMethods.getRoomService()
                .getRoomList(mGetRoomListReq.getDirection(), mGetRoomListReq.getId(),
                        mGetRoomListReq.getType(), mGetRoomListReq.getRoom_tag() == null ? null : mGetRoomListReq.getRoom_tag().name())
                .compose(RxUtil.<ListRes<Room>>applyScheduler())
                .compose(this.<ListRes<Room>>bindToLifecycle())
                .subscribe(new HttpSubscriber<ListRes<Room>>() {
                    @Override
                    protected void onSuccess(ListRes<Room> response) {
                        mBinding.refreshLayout.finishRefresh();
                        
                        loadRecyclerView(response.getResults(), true, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Room> response, int code) {
                        mBinding.refreshLayout.finishRefresh();
                        DialogUtil.showError(mContext, errMsg);
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mGetRoomListReq.nextPage(mAdapter.getLastRoom().getId());
        HttpMethods.getRoomService()
                .getRoomList(mGetRoomListReq.getDirection(), mGetRoomListReq.getId(),
                        mGetRoomListReq.getType(), mGetRoomListReq.getRoom_tag() == null ? null : mGetRoomListReq.getRoom_tag().name())
                .compose(RxUtil.<ListRes<Room>>applyScheduler())
                .compose(this.<ListRes<Room>>bindToLifecycle())
                .subscribe(new HttpSubscriber<ListRes<Room>>() {
                    @Override
                    protected void onSuccess(ListRes<Room> response) {
                        mBinding.refreshLayout.finishLoadmore();
                        
                        loadRecyclerView(response.getResults(), false, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Room> response, int code) {
                        mBinding.refreshLayout.finishLoadmore();
                        DialogUtil.showError(mContext, errMsg);
                    }
                });
    }

    private void loadRecyclerView(List<Room> list, boolean isRefresh, boolean isMore) {
        if (isRefresh) {
            mAdapter.clear();
            mAdapter.add(null, ApartmentAdapter.Type.BANNER.ordinal());
            String[] titles = getResources().getStringArray(R.array.apartment_skill);
            TypedArray ta = getResources().obtainTypedArray(R.array.apartment_skill_icon);
            String[] tags = getResources().getStringArray(R.array.apartment_skill_tag);
            List<SkillViewModel> skillViewModels = new ArrayList<>();
            for (int i = 0; i < titles.length; i++) {
                skillViewModels.add(new SkillViewModel(ta.getResourceId(i, R.drawable.ic_placeholder_square), titles[i], RoomTag.valueOf(tags[i])));
            }
            ta.recycle();
            mAdapter.addAll(skillViewModels, ApartmentAdapter.Type.SKILL.ordinal());

            if (IsEmpty.list(list)) {
                mAdapter.add(null, ApartmentAdapter.Type.EMPTY.ordinal());
            } else {
                mAdapter.addAll(list, ApartmentAdapter.Type.RECOMMEND.ordinal());
            }
        } else {
            mAdapter.addAll(list, ApartmentAdapter.Type.RECOMMEND.ordinal());
        }

        mBinding.refreshLayout.setEnableLoadmore(isMore);
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onCp() {
            ApartmentListActivity.openActivity(mContext, true, null);
        }

        public void onSkill(SkillViewModel item) {
            ApartmentListActivity.openActivity(mContext, false, item.getRoomTag());
        }

        public void enterRoom(Room room) {
            ApartmentDetailActivity.openActivity(mContext, room.getId());
        }
    }

    public static class Util {
        public static String getImage(Room room) {
            return room.getPic();
        }

        public static String getTag(Room room) {
            return App.getInstance().getString(room.getTag().getTitle());
        }

        public static SpannableString getPeople(Room room) {
            SpannableStringBuilder ssb = new SpannableStringBuilder()
                    .append(String.valueOf(room.getMember_count()))
                    .append("人参与");
            ssb.setSpan(
                    new ForegroundColorSpan(
                            App.getInstance().getResources().getColor(R.color.apricot)),
                    0,
                    String.valueOf(room.getMember_count()).length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            );
            return SpannableString.valueOf(ssb);
        }

        public static int getPeopleVisibility(Room room) {
            if (room.getStatus() == RoomStatus.WAITING_FOR_SIGNING) {
                return View.GONE;
            }
            return View.VISIBLE;
        }
    }
}
